using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;

public class ProjectWeaversReader : MarshalByRefObject
{
    public BuildLogger Logger;
    public bool InSolutionWeavingEnabled = true;
    public IList<WeaverEntry> Weavers = new List<WeaverEntry>();
    public ProjectWeaversFinder ProjectWeaversFinder;

    public void Execute()
    {
        if (!ProjectWeaversFinder.Exists)
        {
            return;
        }

        var xDocument = GetDocument(ProjectWeaversFinder.ConfigFilePath);

        var weaversElement = xDocument.Root;
        if (!weaversElement.Name.LocalName.Equals("Weavers", StringComparison.OrdinalIgnoreCase))
        {
            throw new WeavingException(string.Format("Root of '{0}' file should be a Weavers element.", ProjectWeaversFinder.ConfigFileName));
        }

        var inSolutionWeavingEnabledAttribute = weaversElement.Attribute("InSolutionEnabled");
        if (inSolutionWeavingEnabledAttribute != null)
        {
            InSolutionWeavingEnabled = bool.Parse(inSolutionWeavingEnabledAttribute.Value);
        }
        Logger.LogInfo(string.Format("In-solution weaving enabled: {0}.", InSolutionWeavingEnabled));

        foreach (var element in weaversElement.Elements())
        {
            Weavers.Add(new WeaverEntry
                            {
                                Element = element.ToString(SaveOptions.OmitDuplicateNamespaces),
                                AssemblyName = element.Name.LocalName
                            });
        }
    }

    static XDocument GetDocument(string configFilePath)
    {
        try
        {
            return XDocument.Load(configFilePath);
        }
        catch (XmlException exception)
        {
            throw new WeavingException(string.Format(
                "Could not read '{0}' because it has invalid XML." + Environment.NewLine +
                "{1}",
                ProjectWeaversFinder.ConfigFileName, exception.Message));
        }
    }
}